/*
 * @Author: xiaosihan 
 * @Date: 2024-06-22 01:49:44 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-25 15:41:44
 */


import { EllipsisOutlined } from "@ant-design/icons";
import partLableApi from "@api/partCollaborateApi";
import partsApi from "@api/partsApi";
import loginStore from "@views/pc/LoginModal/loginStore";
import userStore from "@views/userStore";
import { Button, Empty, message, Switch, Tooltip } from "antd";
import clsx from "clsx";
import { get, isEmpty } from "lodash";
import { autorun } from "mobx";
import { ReactNode, useEffect, useState } from "react";
import commentModalStore from "../../Model3d/CommentModal/commentModalStore";
import partCollaborateStore from "../../partCollaborateStore";
import styles from "./messageList.module.less";
import notFindPNG from "./notFind.png";

interface Iprops {
    children?: ReactNode
}

// 模型消息列表
export default function MessageList() {

    const getColor = (i: number) => {
        return ["#05D67B", "#5503FA", "#FA6419"][i % 3];
    }

    const userColorMap = new Map<string, string>();

    const [messageApi, contextHolder] = message.useMessage();
    const [partLableDatas, setPartLableDatas] = useState(partCollaborateStore.partLableDatas);
    const [selectLableId, setSelectLableId] = useState(partCollaborateStore.selectLableId);

    useEffect(() => {
        const timer = setInterval(() => {
            partCollaborateStore.getPartLableData();
        }, 5000);

        return () => {
            clearInterval(timer);
        }
    }, []);

    useEffect(() => autorun(() => {
        setPartLableDatas(partCollaborateStore.partLableDatas);
        setSelectLableId(partCollaborateStore.selectLableId);
    }), []);

    function formatTimeDifference(timeString: string): string {
        const inputDate = new Date(timeString);
        const now = new Date();

        // 计算时间差（毫秒）  
        const diff = now.getTime() - inputDate.getTime();

        // 定义时间阈值和对应的输出  
        if (diff < 1000 * 60 * 5) { // 小于5分钟  
            return '刚刚';
        } else if (diff < 1000 * 60 * 60) { // 小于1小时  
            const minutes = Math.floor(diff / (1000 * 60));
            return `${minutes}分钟前`;
        } else if (diff < 1000 * 60 * 60 * 24) { // 小于24小时  
            const hours = Math.floor(diff / (1000 * 60 * 60));
            return `${hours}小时前`;
        } else if (
            diff >= 1000 * 60 * 60 * 24 &&
            diff < 1000 * 60 * 60 * 24 * 2
        ) { // 小于2天  
            // 检查是否是昨天（只考虑日期部分）  
            const yesterday = new Date(now);
            yesterday.setDate(yesterday.getDate() - 1);
            yesterday.setHours(0, 0, 0, 0); // 重置时间为00:00:00  
            if (
                inputDate.getUTCFullYear() === yesterday.getUTCFullYear() &&
                inputDate.getUTCMonth() === yesterday.getUTCMonth() &&
                inputDate.getUTCDate() === yesterday.getUTCDate()
            ) {
                return '昨天';
            }
            // 如果不满足“昨天”的条件，但由于我们已经检查了小于2天，这里实际上不会执行  
            // 但为了代码的完整性，我们仍然可以保留返回小时前的逻辑（尽管它不会被执行）  
            // 或者，你也可以选择返回一个更通用的“1天前”的消息  
            const hours = Math.floor(diff / (1000 * 60 * 60));
            return `${Math.ceil(hours / 24)}天前`; // 或者直接返回 '1天前'，但这样不够准确  
        }

        // 如果时间差超过2天，则返回日期字符串  
        return inputDate.toLocaleDateString();
    }

    //回复评论
    const reply = (modelCommentId: string, replyUserId: string) => {
        if (userStore.isLogin) {
            // 打开评论弹窗
            commentModalStore.setShow(true);
            commentModalStore.setModelIndex();
            commentModalStore.setVPosition({ x: 0, y: 0, z: 0 });
            commentModalStore.setPlaceholder("请输入回复");
            commentModalStore.setModelCommentId(modelCommentId);
            commentModalStore.setReplyUserId(replyUserId);

        } else {
            loginStore.setShowLoginModal(true);
        }
    }

    // 分享链接
    const share_link = async () => {
        const res = await partsApi.getShareToken(partCollaborateStore.modelId);
        const token = get(res, ["data", "token"]);
        const { origin } = location;
        const shareLink = `${origin}/#/partCollaborate/${token}`;
        navigator.clipboard.writeText(shareLink);
        messageApi.success("分享链接已复制到剪贴板!");
    }

    return (
        <div className={styles.messageList} >
            {contextHolder}

            <div className={styles.header} >

                问题
                <span className={styles.num} >数量{partLableDatas.length}</span>

                <span
                    className={styles.hidePoint}
                    onClick={() => {
                        const { hideLable } = partCollaborateStore;
                        partCollaborateStore.setHideLable(!hideLable);
                    }}
                > <Switch size="small" /> 隐藏标点 </span>

            </div>

            {/* 消息列表 */}
            <div className={styles.list} >
                {
                    partLableDatas.map((lableData, i) => {

                        if (!userColorMap.has(lableData.userId)) {
                            userColorMap.set(
                                lableData.userId,
                                getColor(userColorMap.size)
                            );
                        }
                        const color = userColorMap.get(lableData.userId)!;

                        return (
                            <div key={lableData.id} className={styles.list_item} >
                                <span className={styles.index} >
                                    <span
                                        style={{ backgroundColor: color }}
                                        className={styles.number}
                                        onClick={() => {
                                            partCollaborateStore.setSelectLableId(lableData.id);
                                        }}
                                    >{partLableDatas.length - i}</span>
                                </span>
                                <div className={clsx(styles.lable_list, [lableData.id, ""].includes(selectLableId) && styles.show)} >
                                    <div className={styles.lable_item} >

                                        <div
                                            className={clsx(styles.vertical_line, (lableData.details.length === 0) && styles.latest)}
                                        ></div>

                                        <div className={styles.flex} >
                                            <img className={styles.avatar} src={lableData.userAvatarUrl} alt="" />
                                            {/* <div className={[styles.frstName1, styles.frstName2, styles.frstName3][(partLableData.length - i - 1) % 3]}>{(lableData.userName || " ").slice(0, 1)}</div> */}
                                            <div className={styles.content} >
                                                <span className={styles.user_name} >{lableData.userName || "--"}</span>
                                                {lableData.content}
                                            </div>
                                        </div>

                                        <div>
                                            <span className={styles.time} >({formatTimeDifference(lableData.createTime)})</span>
                                            {
                                                (userStore.userId !== lableData.userId) &&
                                                <span className={styles.replyBtn} onClick={() => reply(lableData.id, lableData.userId)} >回复</span>
                                            }
                                            {
                                                userStore.userId === lableData.userId &&
                                                <Tooltip
                                                    rootClassName={styles.delete_tip}
                                                    placement="top"
                                                    mouseEnterDelay={0}
                                                    trigger={["click"]}
                                                    title={
                                                        <Button
                                                            danger
                                                            type="primary"
                                                            size="small"
                                                            onClick={async () => {
                                                                await partLableApi.delete(lableData.id);
                                                                partCollaborateStore.getPartLableData();
                                                            }}
                                                        >确认删除</Button>
                                                    }
                                                >
                                                    {/* 删除 */}
                                                    <EllipsisOutlined
                                                        className={styles.delete}
                                                    />
                                                </Tooltip>
                                            }
                                        </div>
                                    </div>
                                    {
                                        lableData.details.map((detail, ii) => {
                                            return (
                                                <div
                                                    key={detail.id}
                                                    className={styles.lable_item}
                                                >
                                                    <div
                                                        className={clsx(styles.vertical_line, ((ii + 1) === lableData.details.length) && styles.latest)}
                                                    ></div>

                                                    <div className={styles.flex} >
                                                        <img className={styles.avatar} src={detail.userAvatarUrl} alt="" />
                                                        {/* <div className={[styles.frstName1, styles.frstName2, styles.frstName3][(partLableData.length - ii - 1) % 3]}>{["Z", "Q", "T"][i % 3]}</div> */}
                                                        <div className={styles.content} >
                                                            <span className={styles.user_name} >
                                                                {detail.userName || "--"} <span className={styles.reply} >{`回复 ${detail.replyUserName || "--"}`}</span>
                                                            </span>
                                                            {detail.content}
                                                        </div>
                                                    </div>

                                                    <div>
                                                        <span className={styles.time} >({formatTimeDifference(detail.createTime)})</span>
                                                        {
                                                            userStore.userId !== detail.userId &&
                                                            <span className={styles.replyBtn} onClick={() => reply(lableData.id, lableData.userId)} >回复</span>
                                                        }
                                                        {
                                                            userStore.userId === detail.userId &&
                                                            <Tooltip
                                                                rootClassName={styles.delete_tip}
                                                                placement="top"
                                                                mouseEnterDelay={0}
                                                                trigger={["click"]}
                                                                title={
                                                                    <Button
                                                                        danger
                                                                        type="primary"
                                                                        size="small"
                                                                        onClick={async () => {
                                                                            await partLableApi.deleteCommentDetail(detail.id);
                                                                            partCollaborateStore.getPartLableData();
                                                                        }}
                                                                    >确认删除</Button>
                                                                }
                                                            >
                                                                {/* 删除 */}
                                                                <EllipsisOutlined
                                                                    className={styles.delete}
                                                                />
                                                            </Tooltip>
                                                        }
                                                    </div>


                                                </div>
                                            );
                                        })
                                    }
                                </div>
                            </div>
                        );
                    })
                }
                {
                    isEmpty(partLableDatas) &&
                    <Empty
                        className={styles.empty}
                        image={"./notFind.png"}
                        description="暂无评论"
                    />
                }
            </div>
        </div >
    );

}